import { RequestType } from "../AdapterDefine";
import SDKAdatper from "../core/SDKAdatper";
import { SelfAdAdapter } from "../core/SelfAdAdapter";


export class DevRewardAd extends SelfAdAdapter {

    load() {
        this.loadListener.emit()
    }

    show() {
        this.closeListener.emit({ isEnded: true })
    }


}

export class DevSDK extends SDKAdatper {

    createRewardedVideoAd(obj: any) {
        if (!this.hasSDK()) {
            return null;
        }

        return new DevRewardAd(this._sdk, obj)

    }
    request(param: RequestType) {
        let url = param.url
        let data = param.data
        let method: string = param.method ? param.method : "GET"
        let isOk: boolean = false;
        console.log('sendHttpRequest  address ', url)
        let xhr = new XMLHttpRequest();
        xhr.timeout = param.timeout;
        xhr.ontimeout = function () {
            param.fail('ontimeout')
        }
        xhr.onload = function () {
            console.log('onload xhr.status', xhr.status, 'xhr.readyState ', xhr.readyState)
            if (xhr.status >= 200 && xhr.status < 400) {
                if (isOk) {
                    return;
                }
                isOk = true;
                var data = xhr.responseText;
                let temp = { data: data }
                param.success(temp)
            } else {
                param.fail('onload error')
            }
        };
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    if (isOk) {
                        return;
                    }
                    isOk = true;
                    var data = xhr.responseText;
                    let temp = { data: data }
                    param.success(temp)
                } else {
                    param.fail('onload error')
                }
            }
        }
        xhr.open(method, url, true);
        let innerHeaer = param.header;
        if (innerHeaer) {
            for (var key in innerHeaer) {
                if (innerHeaer[key]) {
                    xhr.setRequestHeader(key, innerHeaer[key]);
                }
            }
        }
        try {
            xhr.send(data);
        } catch (error) {
            param.fail('send error ' + error)
        }
    }
}